<template>
	<view class="member-container">
		<view class="header">
			<text class="title">会员中心</text>
		</view>
		
		<view class="member-cards">
			<!-- VIP Card -->
			<view class="member-card" 
				  :class="{ 
					'selected': selectedType === 'MONTHLY', 
					'disabled': currentMemberLevel > 1 || (currentMemberLevel === 1 && !renewMode),
					'current': currentMemberLevel === 1,
					'renew': currentMemberLevel === 1 && renewMode
				  }" 
				  @tap="selectMemberType('MONTHLY')" :disabled="!canSelectType('MONTHLY')">
				<view class="card-header">
					<text class="card-title">月度会员</text>
					<text class="card-price">¥39</text>
				</view>
				<view class="card-content">
					<text class="card-duration">有效期：30天</text>
					<view class="card-benefits">
						<text class="benefit-item">• 专享课程折扣</text>
						<text class="benefit-item">• 优先预约</text>
						<text class="benefit-item">• 专属客服</text>
					</view>
				</view>
				<view class="current-badge" v-if="currentMemberLevel === 1">当前</view>
			</view>
			
			<!-- SVIP Card -->
			<view class="member-card" 
				  :class="{ 
					'selected': selectedType === 'QUARTERLY', 
					'disabled': currentMemberLevel > 2 || (currentMemberLevel === 2 && !renewMode),
					'current': currentMemberLevel === 2,
					'renew': currentMemberLevel === 2 && renewMode
				  }" 
				  @tap="selectMemberType('QUARTERLY')" :disabled="!canSelectType('QUARTERLY')">
				<view class="card-header">
					<text class="card-title">季度会员</text>
					<text class="card-price">¥79</text>
				</view>
				<view class="card-content">
					<text class="card-duration">有效期：90天</text>
					<view class="card-benefits">
						<text class="benefit-item">• 所有VIP特权</text>
						<text class="benefit-item">• 更高课程折扣</text>
						<text class="benefit-item">• 免费课程体验</text>
						<text class="benefit-item">• 24小时专属服务</text>
					</view>
				</view>
				<view class="current-badge" v-if="currentMemberLevel === 2">当前</view>
			</view>
			
			<!-- ANNUAL Card -->
			<view class="member-card" 
				  :class="{ 
					'selected': selectedType === 'ANNUAL', 
					'disabled': currentMemberLevel > 3 || (currentMemberLevel === 3 && !renewMode),
					'current': currentMemberLevel === 3,
					'renew': currentMemberLevel === 3 && renewMode
				  }" 
				  @tap="selectMemberType('ANNUAL')" :disabled="!canSelectType('ANNUAL')">
				<view class="card-header">
					<text class="card-title">年度会员</text>
					<text class="card-price">¥299</text>
				</view>
				<view class="card-content">
					<text class="card-duration">有效期：365天</text>
					<view class="card-benefits">
						<text class="benefit-item">• 所有特权</text>
						<text class="benefit-item">• 最高课程折扣</text>
						<text class="benefit-item">• 不限次课程体验</text>
						<text class="benefit-item">• 全天候专属服务</text>
					</view>
				</view>
				<view class="current-badge" v-if="currentMemberLevel === 3">当前</view>
			</view>
		</view>
		
		<button class="pay-button" @tap="handlePayment" :disabled="!selectedType || !canUpgrade()">
			{{ getButtonText() }}
		</button>
	</view>
</template>

<script>
import request from '@/utils/request.js'
import { payApi } from '@/api/pay.js'

export default {
	data() {
		return {
			selectedType: '',
			renewMode: false,
			memberTypes: {
				MONTHLY: {
					price: 39,
					days: 30,
					name: '月度会员',
					level: 1
				},
				QUARTERLY: {
					price: 79,
					days: 90,
					name: '季度会员',
					level: 2
				},
				ANNUAL: {
					price: 299,
					days: 365,
					name: '年度会员',
					level: 3
				}
			},
			currentMemberLevel: 0
		}
	},
	onLoad() {
		this.getCurrentMembership();
	},
	methods: {
		// 获取当前会员等级
		getCurrentMembership() {
			const userInfo = uni.getStorageSync('userInfo');
			if (userInfo && userInfo.hy) {
				// 假设hy值对应：1=月度会员，2=季度会员，3=年度会员
				this.currentMemberLevel = userInfo.hy;
				console.log('当前会员等级:', this.currentMemberLevel);
				
				// 自动选择当前会员类型
				if (this.currentMemberLevel === 1) {
					this.selectMemberType('MONTHLY');
				} else if (this.currentMemberLevel === 2) {
					this.selectMemberType('QUARTERLY');
				} else if (this.currentMemberLevel === 3) {
					this.selectMemberType('ANNUAL');
				}
			}
		},
		
		// 判断是否可以选择该会员类型（可以续费当前等级或升级）
		canSelectType(type) {
			const typeLevel = this.memberTypes[type].level;
			return typeLevel === this.currentMemberLevel || typeLevel > this.currentMemberLevel;
		},
		
		selectMemberType(type) {
			const typeLevel = this.memberTypes[type].level;
			
			// 如果选择了当前会员类型，设置为续费模式
			if (typeLevel === this.currentMemberLevel) {
				this.selectedType = type;
				this.renewMode = true;
				console.log('进入续费模式:', type);
				return;
			}
			
			// 注意：我们只在实际会员等级高于要选择的等级时，才阻止降级
			// 而不是阻止用户从高级别选项返回到低级别选项
			if (typeLevel < this.currentMemberLevel) {
				uni.showToast({
					title: `您已经是${this.getMembershipName(this.currentMemberLevel)}，不能降级`,
					icon: 'none',
					duration: 2000
				});
				return;
			}
			
			// 允许在未购买前自由选择任何会员类型
			this.selectedType = type;
			this.renewMode = false;
			console.log('选择会员类型:', type);
		},
		
		// 根据会员等级获取会员名称
		getMembershipName(level) {
			switch(level) {
				case 1: return '月度会员';
				case 2: return '季度会员';
				case 3: return '年度会员';
				default: return '普通用户';
			}
		},
		
		async handlePayment() {
			if (!this.selectedType) {
				uni.showToast({
					title: '请选择会员类型',
					icon: 'none'
				});
				return;
			}
			
			// 显示调试信息
			console.log('支付操作 - 选择类型:', this.selectedType);
			console.log('支付操作 - 当前等级:', this.currentMemberLevel);
			console.log('支付操作 - 续费模式:', this.renewMode);
			
			// 检查登录状态
			const userInfo = uni.getStorageSync('userInfo');
			if (!userInfo || !userInfo.id) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				});
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}, 1500);
				return;
			}
			
			const memberInfo = this.memberTypes[this.selectedType]
			
			try {
				uni.showLoading({
					title: '正在创建订单'
				})
				
				// 创建会员订单
				const orderData = {
					type: this.selectedType,
					userId: userInfo.id,
					amount: memberInfo.price
				}
				
				const res = await payApi.createMemberOrder(orderData)
				
				if (res.code === 200 && res.data) {
					const { orderId, paymentUrl } = res.data
					
					// 跳转到支付页面
					uni.navigateTo({
						url: `/pages/payment/webview?html=${encodeURIComponent(paymentUrl)}&orderNo=${orderId}`,
						fail: (err) => {
							console.error('跳转支付页面失败:', err)
							uni.showToast({
								title: '跳转支付页面失败',
								icon: 'none'
							})
						}
					})
				} else {
					throw new Error(res.message || '创建订单失败')
				}
			} catch (error) {
				console.error('支付过程发生错误:', error)
				uni.showToast({
					title: error.message || '支付失败，请重试',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		},
		
		getButtonText() {
			if (!this.selectedType) return '请选择会员类型';
			
			if (this.currentMemberLevel === 0) {
				return `立即开通${this.memberTypes[this.selectedType].name}`;
			} else if (this.renewMode) {
				return `续费${this.memberTypes[this.selectedType].name}`;
			} else {
				return `升级到${this.memberTypes[this.selectedType].name}`;
			}
		},
		
		canUpgrade() {
			// 只要有选择就可以操作
			return !!this.selectedType;
		}
	}
}
</script>

<style>
.member-container {
	padding: 30rpx;
	background-color: #f5f5f5;
	min-height: 100vh;
}

.header {
	margin-bottom: 40rpx;
}

.title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.member-cards {
	display: flex;
	flex-direction: column;
	gap: 30rpx;
}

.member-card {
	background-color: #fff;
	border-radius: 20rpx;
	padding: 30rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
	transition: all 0.3s ease;
}

.member-card.selected {
	border: 2rpx solid #1890ff;
	transform: scale(1.02);
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.card-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.card-price {
	font-size: 40rpx;
	font-weight: bold;
	color: #1890ff;
}

.card-duration {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 20rpx;
}

.card-benefits {
	display: flex;
	flex-direction: column;
	gap: 10rpx;
}

.benefit-item {
	font-size: 26rpx;
	color: #666;
}

.pay-button {
	position: fixed;
	bottom: 40rpx;
	left: 30rpx;
	right: 30rpx;
	height: 88rpx;
	line-height: 88rpx;
	background-color: #1890ff;
	color: #fff;
	border-radius: 44rpx;
	font-size: 32rpx;
	font-weight: bold;
	text-align: center;
}

.pay-button[disabled] {
	background-color: #ccc;
	color: #fff;
}

.member-card.disabled {
	opacity: 0.6;
	pointer-events: none;
	border: 1px solid #eee;
}

.member-card.current {
	opacity: 1;
	border: 2px solid #FFB800;
	position: relative;
}

.member-card.renew {
	border: 2px dashed #FFB800;
	background-color: #FFF9E6;
}

.current-badge {
	position: absolute;
	top: 10rpx;
	right: 10rpx;
	background-color: #FFB800;
	color: #fff;
	padding: 4rpx 16rpx;
	border-radius: 20rpx;
	font-size: 22rpx;
	font-weight: bold;
}
</style> 

